import * as THREE from "three";
// 启用自定义材质，不再使用Three.js内置材质
import { MeshTransmissionMaterial } from "../../materials/MeshTransmissionMaterial";

/**
 * 中间地图层类
 */
export class MidMapLayer {
  constructor(scene, projection, rgbeLoader) {
    this.scene = scene;
    this.projection = projection;
    this.rgbeLoader = rgbeLoader;
    this.mapObject = new THREE.Object3D(); // 地图对象容器
    this.clock = new THREE.Clock(); // 用于动画

    // 预加载纹理
    this.matcapTexture = this.rgbeLoader.load(
      "/model_assets/umhlanga_sunrise_1k.hdr",
      (envMap) => {
        scene.environment = envMap;
        // hdr作为环境贴图生效，设置.mapping为EquirectangularReflectionMapping
        envMap.mapping = THREE.EquirectangularReflectionMapping;

        // 创建高级透明材质 - 在环境贴图加载完成后初始化
        this.createTransmissionMaterial(envMap);
      }
    );
  }

  /**
   * 创建透明材质
   */
  createTransmissionMaterial(envMap) {
    // 使用自定义的MeshTransmissionMaterial，构造函数只接受samples参数
    this.transmissionMaterial = new MeshTransmissionMaterial(16);

    // 设置 MeshPhysicalMaterial 基础属性
    this.transmissionMaterial.color = new THREE.Color("#d2ebff");
    this.transmissionMaterial.ior = 1;
    this.transmissionMaterial.roughness = 0.6;
    this.transmissionMaterial.transmission = 1.0;
    this.transmissionMaterial.thickness = 2; // 增加折射厚度
    // 环境贴图
    this.transmissionMaterial.envMap = envMap;
    this.transmissionMaterial.envMapIntensity = 0.3; // 环境反射强度
    this.transmissionMaterial.clearcoat = 1; // 清漆层
    this.transmissionMaterial.attenuationDistance = 0.4; // 衰减距离
    this.transmissionMaterial.attenuationColor = new THREE.Color("#ffffff"); // 衰减颜色
    this.transmissionMaterial.opacity = 0.1;

    // 设置 MeshTransmissionMaterial 特有的自定义属性
    this.transmissionMaterial.chromaticAberration = 0.3; // 色差效果
    this.transmissionMaterial.anisotrophicBlur = 10.3; // 各向异性模糊
    this.transmissionMaterial.distortion = 8; // 添加一些扭曲效果增强磨砂感
    this.transmissionMaterial.distortionScale = 0.08; // 扭曲比例
    this.transmissionMaterial.temporalDistortion = 0.0; // 时间扭曲

    // 更新所有已创建的网格
    if (this.mapObject) {
      this.mapObject.traverse((obj) => {
        if (obj.isMesh) {
          obj.material = this.transmissionMaterial;
        }
      });
    }
  }

  /**
   * 从GeoJSON数据创建地图
   * @param {Object} jsonData GeoJSON数据
   */
  createFromGeoJson(jsonData) {
    if (!jsonData || !jsonData.features) return;

    const features = jsonData.features;

    features.forEach((feature) => {
      // 单个省份
      const province = new THREE.Object3D();

      // 数据整合
      province.properties = feature.properties.name;
      const coordinates = feature.geometry.coordinates;

      // 多个多边形
      if (feature.geometry.type === "MultiPolygon") {
        coordinates.forEach((coordinate) => {
          coordinate.forEach((rows) => {
            const mesh = this.drawExtrudeMesh(rows);
            province.add(mesh);
          });
        });
      }

      // 单个多边形
      if (feature.geometry.type === "Polygon") {
        coordinates.forEach((coordinate) => {
          const mesh = this.drawExtrudeMesh(coordinate);
          province.add(mesh);
        });
      }

      this.mapObject.add(province);
    });

    this.mapObject.position.z = 0.301; // 基础层0.3 + 中间层1.3 = 1.6
    // 将地图对象添加到场景
    this.scene.add(this.mapObject);

    // 确保场景中有足够的光照
    // this.setupLighting();
  }

  /**
   * 设置场景光照，对透明材质渲染很重要
   */
  setupLighting() {
    // 检查场景中是否已经有足够的光照
    let hasAmbientLight = false;
    let hasDirectionalLight = false;

    this.scene.traverse((obj) => {
      if (obj.isAmbientLight) hasAmbientLight = true;
      if (obj.isDirectionalLight) hasDirectionalLight = true;
    });

    // 如果没有环境光，添加一个
    if (!hasAmbientLight) {
      const ambientLight = new THREE.AmbientLight(0xffffff, 0.5);
      this.scene.add(ambientLight);
    }

    // 如果没有平行光，添加一个
    if (!hasDirectionalLight) {
      const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
      directionalLight.position.set(1, 1, 1);
      this.scene.add(directionalLight);
    }
  }

  /**
   * 绘制立体几何
   * @param {Array} polygon 多边形点数组
   * @returns {THREE.Mesh} 网格对象
   */
  drawExtrudeMesh(polygon) {
    const shape = new THREE.Shape();

    polygon.forEach((row, i) => {
      const [x, y] = this.projection(row);

      if (i === 0) {
        shape.moveTo(x, -y);
      }
      shape.lineTo(x, -y);
    });

    // 挤压缓冲几何 - 中间层高度为1.3
    const geometry = new THREE.ExtrudeGeometry(shape, {
      depth: 0.9,
      bevelEnabled: false,
    });

    // 临时使用基础材质，等环境贴图加载完后会更新
    // const tempMaterial = new THREE.MeshBasicMaterial({
    //   color: "#d2ebff",
    //   transparent: true,
    //   opacity: 0.8,
    // });

    // 如果透明材质已创建则使用它，否则使用临时材质
    const material = this.transmissionMaterial;

    return new THREE.Mesh(geometry, material);
  }

  /**
   * 清理资源
   */
  dispose() {
    if (this.mapObject) {
      this.scene.remove(this.mapObject);

      // 递归遍历所有子对象并释放几何体和材质
      this.mapObject.traverse((obj) => {
        if (obj.isMesh) {
          if (obj.geometry) obj.geometry.dispose();
          if (obj.material) {
            if (Array.isArray(obj.material)) {
              obj.material.forEach((mat) => mat.dispose());
            } else {
              obj.material.dispose();
            }
          }
        }
      });

      // 释放透明材质
      if (this.transmissionMaterial) {
        this.transmissionMaterial.dispose();
      }
    }
  }
}
